package com.lzw.app;

import com.lzw.data.AppRepository;

import java.io.Serializable;
import java.util.*;

/**
 * 注册中心容器对象，用于存储集群信息
 * @author LZW
 */
public class InstanceRepository implements Serializable {
    public static final long serialVersionUID = 2020L;
    private AppRepository appRepository;
    private int orderNum = 0;

    public AppRepository getAppRepository() {
        return appRepository;
    }

    public void setAppRepository(AppRepository appRepository) {
        this.appRepository = appRepository;
    }

    /**
     * 根据实例名称获取instance集合
     *
     * @param name
     * @return
     */
    public List<Instance> getInstancesByName(String name) {
        if (this.appRepository == null) {
            return null;
        }
        Map<String, Instance> instanceMap = appRepository.getData().get(name);
        Collection<Instance> values = instanceMap.values();
        return new ArrayList<Instance>(values);
    }

    /**
     * 根据名称随机获取一个instance
     *
     * @return
     */
    public Instance getInstanceByNameRandom(String name) {
        List<Instance> list = this.getInstancesByName(name);
        if (list == null || list.size() == 0) {
            return null;
        }
        int index = new Random().nextInt(list.size());
        return list.get(index);
    }

    /**
     * 根据名称轮询获取一个instance
     *
     * @return
     */
    public Instance getInstanceByNameOrder(String name) {
        List<Instance> list = this.getInstancesByName(name);
        if (list == null || list.size() == 0) {
            return null;
        }
        if (orderNum >= list.size()) {
            orderNum = 0;
        }
        return list.get(orderNum++);
    }
}
